package middleware

import (
	"gomain/app/service"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

// 检查特定权限
func CheckPermission(permission string) ghttp.HandlerFunc {
	return func(r *ghttp.Request) {
		ctx := r.GetCtx()

		if r.URL.Path == "/api/user/login" {
			g.Log().Debug(ctx, "跳过登录接口的权限检查")
			r.Middleware.Next()
			return
		}

		userId := r.GetCtxVar("user_id").Int()
		if userId == 1 {
			r.Middleware.Next()
			return
		}

		// 获取用户角色
		roles, err := service.User.GetUserRoles(userId)
		if err != nil {
			g.Log().Error(ctx, "获取用户角色失败", err)
			r.Response.WriteJson(g.Map{
				"code": 403,
				"msg":  "无权限访问",
			})
			r.Exit()
		}

		// 检查是否有admin角色
		for _, role := range roles {
			if role.Code == "admin" {
				r.Middleware.Next()
				return
			}
		}

		// 非admin角色，检查具体权限
		hasPermission, err := service.User.CheckPermission(userId, permission)
		if err != nil {
			g.Log().Error(ctx, "检查权限失败", err)
			r.Response.WriteJson(g.Map{
				"code": 403,
				"msg":  "无权限访问",
			})
			r.Exit()
		}

		if !hasPermission {
			g.Log().Warning(ctx, "无权限访问", "userId", userId, "permission", permission)
			r.Response.WriteJson(g.Map{
				"code": 403,
				"msg":  "无权限访问",
			})
			r.Exit()
		}

		r.Middleware.Next()
	}
}
